<template>
  <view class="rich-text-page">
    <!-- 头部样式 -->
    <view class="header">
      <view class="back-button" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="title">{{ pageTitle }}</view>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view 
      scroll-y="true" 
      class="content-area" 
      :enhanced="true"
      :bounces="true"
      :show-scrollbar="true">
      
      <!-- 富文本内容渲染器 - 已整合 -->
      <view v-if="richTextContent" class="quill-rich-text-renderer">
        <!-- 加载状态 -->
        <view v-if="rendererLoading" class="loading-state">
          正在加载内容...
        </view>
        
        <!-- 错误状态 -->
        <view v-else-if="rendererError" class="error-state">
          {{ rendererError }}
        </view>
        
        <!-- 空内容状态 -->
        <view v-else-if="!hasRendererContent" class="empty-state">
          暂无内容
        </view>
        
        <!-- 富文本内容 -->
        <view v-else class="content-container">
          <rich-text
            class="rich-text-content"
            :nodes="processedNodes"
            :selectable="true"
            @tap="handleContentTap"
          />
        </view>
      </view>
      
      <!-- 错误信息显示 -->
      <view class="error-message" v-else-if="errorMessage">
        <text>{{ errorMessage }}</text>
      </view>
      
      <!-- 加载中提示 -->
      <view class="loading-message" v-else-if="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 底部空间 -->
      <view class="bottom-space"></view>
    </scroll-view>
    
    <!-- 底部更新时间 -->
    <view class="bottom-meta" v-if="itemData && !loading && !errorMessage">
      <text class="update-time-bottom">更新时间：{{ formatUpdateTime(itemData.updated_at) }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import api from '@/common/api/content.js'

/**
 * 富文本页面组件
 * 用于展示从管理端创建的富文本内容
 */

// 页面数据
const loading = ref(true)
const errorMessage = ref('')
const itemData = ref(null)
const richTextContent = ref('')
const contentType = ref('auto')

// 渲染器相关数据
const rendererLoading = ref(false)
const rendererError = ref('')
const processedNodes = ref([])
const detectedBackground = ref('#ffffff')
const backgroundDetectionTimer = ref(null)

// 页面参数
const itemId = ref('')
const categoryId = ref('')

// 自定义样式
const customStyle = ref({
  fontSize: '16px',
  lineHeight: '1.6',
  color: '#333333',
  padding: '20px'
})

/**
 * 渲染器计算属性 - 检查是否有内容
 */
const hasRendererContent = computed(() => {
  return processedNodes.value && processedNodes.value.length > 0
})

/**
 * 容器样式
 */
const containerStyle = computed(() => {
  const baseStyle = {
    backgroundColor: 'transparent',
    color: '#333333'
  }
  
  // 根据检测到的背景色调整文字颜色
  if (detectedBackground.value) {
    const bgColor = detectedBackground.value.toLowerCase()
    if (bgColor.includes('#000') || bgColor.includes('black') || bgColor.includes('dark')) {
      baseStyle.color = '#ffffff'
    }
  }
  
  return baseStyle
})

/**
 * 页面标题
 */
const pageTitle = computed(() => {
  return itemData.value?.name || '富文本内容'
})

// 移除标题融合逻辑，标题现在显示在头部

/**
 * 获取页面参数
 */
const getPageParams = () => {
  // H5环境下从URL获取参数
  // #ifdef H5
  if (typeof window !== 'undefined' && window.location) {
    const urlParams = new URLSearchParams(window.location.search)
    const hash = window.location.hash
    
    // 从hash中解析参数
    if (hash.includes('?')) {
      const hashParams = new URLSearchParams(hash.split('?')[1])
      itemId.value = hashParams.get('itemId') || hashParams.get('id') || ''
      categoryId.value = hashParams.get('categoryId') || ''
    }
    
    // 如果hash中没有参数，尝试从search中获取
    if (!itemId.value) {
      itemId.value = urlParams.get('itemId') || urlParams.get('id') || ''
      categoryId.value = urlParams.get('categoryId') || ''
    }
    
    console.log('🔍 H5环境URL参数解析:', {
      url: window.location.href,
      hash: hash,
      search: window.location.search,
      itemId: itemId.value,
      categoryId: categoryId.value
    })
  }
  // #endif
  
  // 小程序环境下使用getCurrentPages
  // #ifndef H5
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  itemId.value = options.itemId || options.id || ''
  categoryId.value = options.categoryId || ''
  
  console.log('🔍 小程序环境页面参数:', { itemId: itemId.value, categoryId: categoryId.value })
  // #endif
}

/**
 * 验证内容是否有效
 * @param {string} content - 内容字符串
 * @returns {boolean} 是否有效
 */
const isValidContent = (content) => {
  if (!content || typeof content !== 'string') {
    return false;
  }
  // 去除HTML标签和空白字符后检查是否还有内容
  const textContent = content.replace(/<[^>]*>/g, '').trim();
  return textContent.length > 0;
};

/**
 * 处理内容类型和格式
 * @param {object} data - API返回的数据
 * @returns {object} 处理后的内容信息
 */
const processContentData = (data) => {
  console.log('🔍 processContentData 开始处理数据:', data)
  const result = {
    content: '',
    type: 'text',
    isValid: false
  };

  if (!data || !data.content) {
    console.log('🔍 processContentData: 数据为空或无内容')
    return result;
  }

  const content = data.content;
  const contentType = data.content_type || 'text';
  console.log('🔍 processContentData: 原始内容类型=', contentType, '内容长度=', content.length)
  console.log('🔍 processContentData: 内容预览=', content.substring(0, 200))

  // 验证内容是否有效
  if (!isValidContent(content)) {
    console.log('🔍 processContentData: 内容验证失败，无有效内容')
    return result;
  }

  // 根据content_type处理内容
  switch (contentType) {
    case 'rich_text':
      // rich_text类型需要解析JSON格式的内容
      try {
        const parsedContent = JSON.parse(content);
        if (parsedContent.html) {
          result.content = parsedContent.html;
          result.type = 'html';
          result.isValid = true;
          console.log('🔍 processContentData: rich_text类型，解析JSON成功，提取html字段')
        } else {
          // 如果没有html字段，直接使用原内容
          result.content = content;
          result.type = 'html';
          result.isValid = true;
          console.log('🔍 processContentData: rich_text类型，JSON中无html字段，使用原内容')
        }
      } catch (e) {
        // JSON解析失败，直接当作HTML处理
        result.content = content;
        result.type = 'html';
        result.isValid = true;
        console.log('🔍 processContentData: rich_text类型，JSON解析失败，直接当作HTML处理')
      }
      break;
    case 'html':
      result.content = content;
      result.type = 'html';
      result.isValid = true;
      console.log('🔍 processContentData: html类型')
      break;
    case 'markdown':
      // Markdown内容也当作HTML处理（假设后端已转换）
      result.content = content;
      result.type = 'html';
      result.isValid = true;
      console.log('🔍 processContentData: markdown类型，设置为html模式')
      break;
    case 'text':
    default:
      // 纯文本内容
      result.content = content;
      result.type = 'text';
      result.isValid = true;
      console.log('🔍 processContentData: 纯文本类型')
      break;
  }

  console.log('🔍 processContentData: 处理结果=', {
    type: result.type,
    isValid: result.isValid,
    contentLength: result.content.length,
    contentPreview: result.content.substring(0, 100)
  })
  
  return result;
};

/**
 * 加载富文本内容（优化版）
 */
const loadRichTextContent = async () => {
  try {
    loading.value = true;
    errorMessage.value = '';
    richTextContent.value = '';
    contentType.value = 'text';

    // 参数验证
    if (!itemId.value) {
      throw new Error('缺少项目ID参数');
    }

    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true
    });

    console.log('🚀 开始加载内容，itemId:', itemId.value);
    console.log('🔗 API基础URL检查:', 'http://localhost:8080');
    console.log('🎯 完整请求URL:', `http://localhost:8080/api/v1/items/${itemId.value}`);

    // 调用API获取内容
    console.log('📡 正在发送API请求...');
    const response = await api.item.getItem(itemId.value);

    console.log('✅ API响应成功:', {
      success: !!response?.data,
      hasContent: !!response?.data?.content,
      contentType: response?.data?.content_type,
      contentLength: response?.data?.content?.length || 0,
      fullResponse: response
    });

    if (!response || !response.data) {
      throw new Error(response?.message || '获取内容失败');
    }

    const data = response.data;
    itemData.value = data;

    // 更新页面标题
    if (data.name) {
      uni.setNavigationBarTitle({
        title: data.name
      });
    }

    // 处理内容数据
    const contentInfo = processContentData(data);

    if (!contentInfo.isValid) {
      throw new Error('该项目暂无有效内容');
    }

    // 设置内容
    richTextContent.value = contentInfo.content;
    contentType.value = contentInfo.type;

    console.log('内容加载成功:', {
      type: contentInfo.type,
      length: contentInfo.content.length,
      preview: contentInfo.content.substring(0, 100)
    });

    // 隐藏加载提示
    uni.hideLoading();

  } catch (error) {
    console.error('加载富文本内容失败:', error);
    
    // 隐藏加载提示
    uni.hideLoading();
    
    // 设置错误信息
    const errorMsg = error.message || '网络请求失败';
    errorMessage.value = errorMsg;
    
    // 显示错误提示
    uni.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 3000
    });
    
  } finally {
    loading.value = false;
  }
};

/**
 * 处理内容点击事件
 */
const handleContentTap = (event) => {
  // console.log('内容被点击:', event)
  // 可以在这里处理链接跳转等逻辑
}

/**
 * 解析HTML内容
 * @param {string} html - HTML字符串
 * @returns {string} 处理后的HTML
 */
function parseHtml(html) {
  if (!html || typeof html !== 'string') {
    return ''
  }
  
  console.log('开始解析HTML内容')
  
  let processedHtml = html
  
  // 处理代码块，添加主题类名和语言标签
  processedHtml = processedHtml.replace(
    /<pre([^>]*class="([^"]*ql-syntax[^"]*)")[^>]*>/g,
    (match, attrs, className) => {
      console.log('找到代码块:', match)
      
      // 检查是否已经有主题类名
      const allThemeClasses = [
        'code-default', 'code-dark', 'code-github', 'code-vscode', 'code-terminal', 'code-minimal', 
        'code-colorful', 'code-gradient', 'code-tip', 'code-warning', 'code-info', 'code-success', 
        'code-error', 'code-note'
      ]
      
      const hasTheme = allThemeClasses.some(themeClass => className.includes(themeClass))
      
      // 如果没有主题类名，添加默认主题
      let updatedClassName = className
      if (!hasTheme) {
        updatedClassName = className + ' code-default'
      }
      
      // 检测编程语言
      let language = 'code'
      const codeContent = processedHtml.match(new RegExp(match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([\\s\\S]*?)</pre>'))
      if (codeContent && codeContent[1]) {
        const content = codeContent[1].trim()
        // 简单的语言检测
        if (content.includes('function') || content.includes('const') || content.includes('let')) {
          language = 'javascript'
        } else if (content.includes('def ') || content.includes('import ')) {
          language = 'python'
        } else if (content.includes('#include') || content.includes('int main')) {
          language = 'cpp'
        } else if (content.includes('public class') || content.includes('System.out')) {
          language = 'java'
        } else if (content.includes('<html>') || content.includes('<div>')) {
          language = 'html'
        } else if (content.includes('body {') || content.includes('.class')) {
          language = 'css'
        }
      }
      
      console.log('处理代码块:', {
        hasTheme,
        className: updatedClassName,
        language,
        content: codeContent && codeContent[1] ? codeContent[1].substring(0, 50) + '...' : ''
      })
      
      // 添加语言标签属性和更新的类名
      const newAttrs = attrs.replace(`class="${className}"`, `data-language="${language}" class="${updatedClassName}"`)
      
      return `<pre${newAttrs}>`
    }
  )
  
  console.log('HTML解析完成')
  return processedHtml
}

/**
 * 解析Delta内容
 * @param {Object} delta - Delta对象
 * @returns {string} 转换后的HTML
 */
function parseDelta(delta) {
  if (!delta || typeof delta !== 'object') {
    return ''
  }
  
  console.log('开始解析Delta内容')
  
  // 简单的Delta到HTML转换
  let html = ''
  if (delta.ops && Array.isArray(delta.ops)) {
    delta.ops.forEach(op => {
      if (op.insert) {
        if (typeof op.insert === 'string') {
          let text = op.insert
          if (op.attributes) {
            if (op.attributes.bold) text = `<strong>${text}</strong>`
            if (op.attributes.italic) text = `<em>${text}</em>`
            if (op.attributes.underline) text = `<u>${text}</u>`
            if (op.attributes.code) text = `<code>${text}</code>`
          }
          html += text
        }
      }
    })
  }
  
  console.log('Delta解析完成')
  return parseHtml(html)
}

/**
 * 解析纯文本内容
 * @param {string} text - 纯文本
 * @returns {string} 转换后的HTML
 */
function parseText(text) {
  if (!text || typeof text !== 'string') {
    return ''
  }
  
  console.log('开始解析纯文本内容')
  
  // 将换行符转换为段落
  const paragraphs = text.split('\n').filter(p => p.trim())
  const html = paragraphs.map(p => `<p>${p}</p>`).join('')
  
  console.log('纯文本解析完成')
  return html
}

/**
 * 处理内容 - 核心处理函数
 * @param {string} content - 内容
 * @param {string} type - 内容类型
 */
function processContent(content, type) {
  console.log('开始处理内容:', { content: content?.substring(0, 100) + '...', type })
  
  if (!content) {
    processedNodes.value = []
    rendererError.value = ''
    rendererLoading.value = false
    return
  }
  
  try {
    rendererLoading.value = true
    rendererError.value = ''
    
    let processedHtml = ''
    
    switch (type) {
      case 'html':
        processedHtml = parseHtml(content)
        break
      case 'delta':
        try {
          const deltaObj = typeof content === 'string' ? JSON.parse(content) : content
          processedHtml = parseDelta(deltaObj)
        } catch (e) {
          console.error('Delta解析失败，尝试作为HTML处理:', e)
          processedHtml = parseHtml(content)
        }
        break
      case 'auto':
      default:
        // 自动检测内容类型
        if (typeof content === 'object' && content.ops) {
          processedHtml = parseDelta(content)
        } else if (typeof content === 'string') {
          if (content.trim().startsWith('<') || content.includes('<p>') || content.includes('<div>')) {
            processedHtml = parseHtml(content)
          } else {
            processedHtml = parseText(content)
          }
        } else {
          processedHtml = parseText(String(content))
        }
        break
    }
    
    // 转换为rich-text组件需要的nodes格式
    if (processedHtml) {
      processedNodes.value = processedHtml
    } else {
      processedNodes.value = []
    }
    
    console.log('内容处理完成:', { nodesLength: processedNodes.value.length })
  } catch (error) {
    console.error('内容处理失败:', error)
    rendererError.value = '内容处理失败: ' + error.message
    processedNodes.value = []
  } finally {
    rendererLoading.value = false
  }
}

/**
 * 格式化更新时间
 * @param {string} dateString - 时间字符串
 * @returns {string} 格式化后的时间
 */
const formatUpdateTime = (dateString) => {
  if (!dateString) return '未知时间'
  
  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return '时间格式错误'
  }
}

/**
 * 返回首页
 */
const goBack = () => {
  // 直接跳转到首页
  uni.reLaunch({
    url: '/pages/home/home'
  })
}

/**
 * 分享功能
 */
const onShareAppMessage = () => {
  return {
    title: pageTitle.value,
    path: `/pages/rich-text/rich-text?itemId=${itemId.value}&categoryId=${categoryId.value}`
  }
}

/**
 * 分享到朋友圈
 */
const onShareTimeline = () => {
  return {
    title: pageTitle.value,
    query: `itemId=${itemId.value}&categoryId=${categoryId.value}`
  }
}

/**
 * 背景色自动检测（仅在非小程序环境下）
 */
function detectPageBackground() {
  // #ifdef H5
  try {
    const body = document.body
    const computedStyle = window.getComputedStyle(body)
    const bgColor = computedStyle.backgroundColor
    
    if (bgColor && bgColor !== 'rgba(0, 0, 0, 0)' && bgColor !== 'transparent') {
      detectedBackground.value = bgColor
      console.log('检测到页面背景色:', bgColor)
    }
  } catch (error) {
    console.warn('背景色检测失败:', error)
  }
  // #endif
}

// 监听内容变化
watch(() => richTextContent.value, (newContent) => {
  if (newContent) {
    processContent(newContent, contentType.value)
  }
}, { immediate: true })

watch(() => contentType.value, (newType) => {
  if (richTextContent.value) {
    processContent(richTextContent.value, newType)
  }
})

// 页面生命周期
onMounted(() => {
  console.log('🔍 rich-text.vue 页面已加载')
  console.log('🔍 当前页面路径:', 'pages/rich-text/rich-text.vue')
  getPageParams()
  console.log('🔍 获取到的参数 - itemId:', itemId.value, 'categoryId:', categoryId.value)
  
  // 启动背景色检测
  // #ifdef H5
  backgroundDetectionTimer.value = setInterval(detectPageBackground, 1000)
  // #endif
  
  loadRichTextContent()
})

// 清理定时器
// #ifdef H5
onUnmounted(() => {
  if (backgroundDetectionTimer.value) {
    clearInterval(backgroundDetectionTimer.value)
    backgroundDetectionTimer.value = null
  }
})
// #endif

// 导出分享方法供小程序使用
defineExpose({
  onShareAppMessage,
  onShareTimeline
})
</script>

<style scoped>
/* 重置页面默认样式 */
page {
  margin: 0;
  padding: 0;
  background-color: transparent;
}

.rich-text-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff;
  margin: 0;
  padding: 0;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  padding: calc(20rpx + 44px) 0 20rpx;
  background-color: #1e3c72;
  color: #fff;
  position: relative;
  margin: 0;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  margin-right: 20rpx;
}

.back-icon {
  font-size: 32rpx;
  font-weight: bold;
}

.title {
  flex: 1;
  font-size: 36rpx;
  font-weight: 600;
  text-align: center;
  margin-right: 80rpx;
}

/* 内容区域样式 */
.content-area {
  flex: 1;
  padding: 0;
  margin: 0;
  overflow-y: auto;
}

/* 底部空间 */
.bottom-space {
  height: 0;
  margin: 0;
  padding: 0;
}

/* 底部更新时间样式 - 美化版 */
.bottom-meta {
  position: relative;
  width: 100%;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.98) 100%);
  backdrop-filter: blur(25px) saturate(220%);
  padding: 20px 30px 25px;
  border-top: 2px solid rgba(30, 60, 114, 0.1);
  text-align: center;
  z-index: 100;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.08), 0 -2px 12px rgba(0, 0, 0, 0.06);
  margin: 0;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.bottom-meta::before {
  content: '';
  position: absolute;
  top: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #1e3c72 0%, #2a5298 50%, #1e3c72 100%);
  border-radius: 2px;
  opacity: 0.7;
  box-shadow: 0 2px 8px rgba(30, 60, 114, 0.3);
}

.bottom-meta::after {
  content: '';
  position: absolute;
  top: 12px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background: linear-gradient(90deg, transparent 0%, rgba(30, 60, 114, 0.2) 50%, transparent 100%);
  border-radius: 1px;
}

.update-time-bottom {
  font-size: 14px;
  color: #1e3c72;
  font-weight: 600;
  letter-spacing: 0.3px;
  margin-top: 8px;
  text-shadow: 0 2px 4px rgba(255, 255, 255, 0.8);
  opacity: 0.9;
  line-height: 1.4;
  position: relative;
}

.update-time-bottom::before {
  content: '🕒';
  margin-right: 6px;
  font-size: 13px;
  opacity: 0.8;
}

/* 悬浮效果 */
.bottom-meta:hover {
  transform: translateY(-2px);
  box-shadow: 0 -12px 40px rgba(0, 0, 0, 0.12), 0 -4px 16px rgba(0, 0, 0, 0.08);
}

.bottom-meta:hover::before {
  opacity: 1;
  width: 100px;
  box-shadow: 0 3px 12px rgba(30, 60, 114, 0.4);
}

.bottom-meta:hover .update-time-bottom {
  color: #2a5298;
  opacity: 1;
}

/* 移除浮动控制按钮样式，返回按钮现在在头部 */

.error-message {
  padding: 20px;
  margin: 0;
  text-align: center;
  color: #ff6b6b;
  background-color: #fff5f5;
  border: 1px solid #ffebee;
  border-radius: 0;
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-message {
  padding: 20px;
  margin: 0;
  text-align: center;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 0;
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .navbar {
    padding: 0 10px;
  }
  
  .nav-left,
  .nav-right {
    width: 50px;
  }
  
  .nav-title text {
    font-size: 16px;
  }
}

/* ===== 整合的QuillRichTextRenderer样式 ===== */
.quill-rich-text-renderer {
  width: 100%;
  min-height: 10vh;
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.loading-state,
.error-state,
.empty-state {
  padding: 20px;
  margin: 0;
  text-align: center;
  color: #666;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-state {
  color: #e74c3c;
}

.content-container {
  width: 100%;
  padding: 0;
  margin: 0;
}

.rich-text-content {
  width: 100%;
  background: transparent;
  padding: 0;
  margin: 0;
}

/* 融合标题样式 */
.rich-text-content /deep/ .integrated-title {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.95) 100%);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

.rich-text-content /deep/ .integrated-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20px;
  right: 20px;
  height: 2px;
  background: linear-gradient(90deg, #007aff 0%, #34c759 50%, #007aff 100%);
  border-radius: 1px;
  opacity: 0.6;
}

.rich-text-content /deep/ .integrated-title .title-text {
  font-size: 32px;
  font-weight: 800;
  color: #1a1a1a;
  line-height: 1.2;
  margin: 0;
  padding: 0;
  word-break: break-word;
  text-align: left;
  border: none;
  background: transparent;
  letter-spacing: -0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: block;
}

/* 确保代码块内所有元素都有正确的背景 */
.rich-text-content /deep/ .ql-syntax {
  background: inherit !important;
}

.rich-text-content /deep/ .ql-syntax .ql-code-text,
.rich-text-content /deep/ .ql-syntax .ql-code-view {
  background: inherit !important;
}

/* 代码块基础样式 */
.rich-text-content /deep/ .ql-syntax {
  display: block !important;
  width: 100% !important;
  box-sizing: border-box !important;
}

/* 代码块样式 - 默认样式 */
.rich-text-content /deep/ .ql-syntax.code-default,
.rich-text-content /deep/ .ql-syntax:not([class*="code-"]) {
  background-color: #f8f8f8 !important;
  color: #333333 !important;
  border: 1px solid #e1e4e8 !important;
  border-radius: 6px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

/* 代码块样式 - 暗色主题 */
.rich-text-content /deep/ .ql-syntax.code-dark {
  background-color: #2d3748 !important;
  color: #e2e8f0 !important;
  border: 1px solid #4a5568 !important;
  border-radius: 6px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

/* 代码块样式 - GitHub风格 */
.rich-text-content /deep/ .ql-syntax.code-github {
  background-color: #f6f8fa !important;
  color: #24292e !important;
  border: 1px solid #d0d7de !important;
  border-radius: 6px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12) !important;
}

/* 代码块样式 - VS Code风格 */
.rich-text-content /deep/ .ql-syntax.code-vscode {
  background-color: #1e1e1e !important;
  color: #d4d4d4 !important;
  border-left: 3px solid #007acc !important;
  border-radius: 4px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3) !important;
}

/* 代码块样式 - 终端风格 */
.rich-text-content /deep/ .ql-syntax.code-terminal {
  background-color: #0c0c0c !important;
  color: #00ff41 !important;
  border: 2px solid #333 !important;
  border-radius: 0 !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Courier New', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  text-shadow: 0 0 5px #00ff41 !important;
  box-shadow: inset 0 0 10px rgba(0, 255, 65, 0.1) !important;
}

/* 代码块样式 - 简约风格 */
.rich-text-content /deep/ .ql-syntax.code-minimal {
  background-color: #fafafa !important;
  color: #666666 !important;
  border: none !important;
  border-left: 4px solid #ddd !important;
  border-radius: 0 !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Monaco', 'Menlo', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: none !important;
}

/* 代码块样式 - 彩色边框 */
.rich-text-content /deep/ .ql-syntax.code-colorful {
  background-color: #2d3748 !important;
  color: #e2e8f0 !important;
  border: 3px solid transparent !important;
  border-image: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4, #ffeaa7) 1 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Fira Code', 'Consolas', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

/* 代码块样式 - 渐变背景 */
.rich-text-content /deep/ .ql-syntax.code-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: #ffffff !important;
  border: none !important;
  border-radius: 12px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Fira Code', 'SF Mono', monospace !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3), 0 3px 10px rgba(118, 75, 162, 0.2) !important;
  position: relative !important;
}

/* 代码块样式 - 提示信息 */
.rich-text-content /deep/ .ql-syntax.code-tip {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%) !important;
  color: #0369a1 !important;
  border: 1px solid #0ea5e9 !important;
  border-left: 4px solid #0ea5e9 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(14, 165, 233, 0.15), 0 2px 4px rgba(14, 165, 233, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-tip::before {
  content: "💡" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* 代码块样式 - 警告提醒 */
.rich-text-content /deep/ .ql-syntax.code-warning {
  background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%) !important;
  color: #92400e !important;
  border: 1px solid #f59e0b !important;
  border-left: 4px solid #f59e0b !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.15), 0 2px 4px rgba(245, 158, 11, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-warning::before {
  content: "⚠️" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* 代码块样式 - 重要信息 */
.rich-text-content /deep/ .ql-syntax.code-info {
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%) !important;
  color: #1e40af !important;
  border: 1px solid #3b82f6 !important;
  border-left: 4px solid #3b82f6 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15), 0 2px 4px rgba(59, 130, 246, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-info::before {
  content: "ℹ️" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* 代码块样式 - 成功提示 */
.rich-text-content /deep/ .ql-syntax.code-success {
  background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%) !important;
  color: #166534 !important;
  border: 1px solid #22c55e !important;
  border-left: 4px solid #22c55e !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.15), 0 2px 4px rgba(34, 197, 94, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-success::before {
  content: "✅" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* 代码块样式 - 错误提示 */
.rich-text-content /deep/ .ql-syntax.code-error {
  background: linear-gradient(135deg, #fef2f2 0%, #fecaca 100%) !important;
  color: #991b1b !important;
  border: 1px solid #ef4444 !important;
  border-left: 4px solid #ef4444 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.15), 0 2px 4px rgba(239, 68, 68, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-error::before {
  content: "❌" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* 代码块样式 - 笔记备注 */
.rich-text-content /deep/ .ql-syntax.code-note {
  background: linear-gradient(135deg, #faf5ff 0%, #f3e8ff 100%) !important;
  color: #7c3aed !important;
  border: 1px solid #8b5cf6 !important;
  border-left: 4px solid #8b5cf6 !important;
  border-radius: 8px !important;
  padding: 16px !important;
  margin: 16px 0 !important;
  font-family: 'Inter', 'SF Pro Display', -apple-system, sans-serif !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  overflow-x: auto !important;
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.15), 0 2px 4px rgba(139, 92, 246, 0.1) !important;
  position: relative !important;
}

.rich-text-content /deep/ .ql-syntax.code-note::before {
  content: "📝" !important;
  position: absolute !important;
  left: 16px !important;
  top: 18px !important;
  font-size: 18px !important;
}

/* ===== VS Code Dark+ 主题语法高亮 ===== */
.rich-text-content /deep/ .token.comment,
.rich-text-content /deep/ .token.prolog,
.rich-text-content /deep/ .token.doctype,
.rich-text-content /deep/ .token.cdata {
  color: #6a9955 !important;
  font-style: italic !important;
}

.rich-text-content /deep/ .token.punctuation {
  color: #cccccc !important;
}

.rich-text-content /deep/ .token.property,
.rich-text-content /deep/ .token.tag,
.rich-text-content /deep/ .token.boolean,
.rich-text-content /deep/ .token.number,
.rich-text-content /deep/ .token.constant,
.rich-text-content /deep/ .token.symbol,
.rich-text-content /deep/ .token.deleted {
  color: #b5cea8 !important;
}

.rich-text-content /deep/ .token.selector,
.rich-text-content /deep/ .token.attr-name,
.rich-text-content /deep/ .token.string,
.rich-text-content /deep/ .token.char,
.rich-text-content /deep/ .token.builtin,
.rich-text-content /deep/ .token.inserted {
  color: #ce9178 !important;
}

.rich-text-content /deep/ .token.operator,
.rich-text-content /deep/ .token.entity,
.rich-text-content /deep/ .token.url {
  color: #d4d4d4 !important;
}

.rich-text-content /deep/ .token.atrule,
.rich-text-content /deep/ .token.attr-value,
.rich-text-content /deep/ .token.keyword {
  color: #569cd6 !important;
}

.rich-text-content /deep/ .token.function,
.rich-text-content /deep/ .token.class-name {
  color: #dcdcaa !important;
}

.rich-text-content /deep/ .token.regex,
.rich-text-content /deep/ .token.important,
.rich-text-content /deep/ .token.variable {
  color: #9cdcfe !important;
}

.rich-text-content /deep/ .token.important,
.rich-text-content /deep/ .token.bold {
  font-weight: bold !important;
}

.rich-text-content /deep/ .token.italic {
  font-style: italic !important;
}

/* 空段落样式 */
.rich-text-content /deep/ div[style*="height: 1em"] {
  height: 1em !important;
  min-height: 1em !important;
}

/* 深色模式支持 - 注释掉以支持动态背景色 */
/* @media (prefers-color-scheme: dark) {
  .rich-text-page {
    background-color: #1a1a1a;
  }
  
  .navbar {
    background-color: #1a1a1a;
    border-bottom-color: #333333;
  }
  
  .nav-title text {
    color: #ffffff;
  }
  
  .content-wrapper {
    background-color: #1a1a1a;
  }
} */
</style>